package com.zbkj.crmeb.task.plat.bieyang;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crmeb.core.config.RestTemplateConfig;
import com.crmeb.core.utils.TableNameUtil;
import com.factory.TaskParamsDto;
import com.utils.DateUtil;
import com.utils.PriceUtil;
import com.utils.ProductUtil;
import com.utils.SpringBeanUtil;
import com.utils.monitor.DingMsgEnum;
import com.utils.monitor.DingTalkMsgUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.enums.BusinessTypeEnums;
import com.zbkj.crmeb.enums.CategoryTypeEnum;
import com.zbkj.crmeb.enums.plat.PlatPushStatusEnums;
import com.zbkj.crmeb.handler.orderproduct.FileUploadUtils;
import com.zbkj.crmeb.handler.orderproduct.OrderProductContext;
import com.zbkj.crmeb.handler.orderproduct.OrderProductInterface;
import com.zbkj.crmeb.merchant.admin.service.MerStoreProductService;
import com.zbkj.crmeb.plat.by.dto.*;
import com.zbkj.crmeb.plat.by.dto.attributes.SaleAttribute;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.dao.StoreProductDao;
import com.zbkj.crmeb.store.dto.product.StoreProductQueryDTO;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.response.StoreCartResponse;
import com.zbkj.crmeb.store.response.StoreProductCartProductInfoResponse;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.task.plat.AbstractPlatOperate;
import com.zbkj.crmeb.task.plat.bieyang.dto.*;
import com.zbkj.crmeb.tools.service.MoneyExchangeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 别样订单捞取
 *
 * @author: wsl
 * @date: 2024/1/29 0029 22:08
 * @ClassName: BieYangOrderTask
 */
@Component("BieYangTestTask")
@Configuration
@Slf4j
public class BieYangTestTask implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(BieYangTestTask.class);
    @Autowired
    RestTemplateConfig restTemplateConfig;
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private MerStoreProductService merStoreProductService;
    @Autowired
    private RelationService relationService;
    @Autowired
    private StoreProductAttrService storeProductAttrService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Resource
    private StoreOrderDao storeOrderDao;
    @Resource
    private StoreBrandService storeBrandService;
    @Resource
    private ICategoryMatchService categoryMatchService;
    @Resource
    private PriceUtil priceUtil;
    @Resource
    private MoneyExchangeService moneyExchangeService;
    @Resource
    private CustomsRecordService customRecordService;


    @Qualifier("byOrderProductHandler")
    @Autowired
    private OrderProductInterface orderProductInterface;

//    @Value("${by.plat.url}")
    private static String platUrl = "https://eurus-prod.bybieyang.com";

    private static String platKey = "Bearer bxl_live_9264a1983cdb4d30a06477a574aef7fe";
//    @Value("${by.plat.key}")
    public void setKey(String key) {
        platKey = key;
    }

    @Resource
    private StoreProductDao storeProductDao;

    @Resource
    private ProductUtil productUtil;

    @Override
    public void run(ApplicationArguments args) throws Exception {
//        fix();
//        doTest();
//        fixV2();
//        pushMainImage();
//        initCustoms();
    }
    public void doTest(){
        List<StoreProduct> productList = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery().eq(StoreProduct::getIsEurope, "23"));
//        List<String> productIds = new ArrayList<>();
//        for (StoreProduct storeProduct : productList) {
//            productIds.add(String.valueOf(storeProduct.getId()));
//        }
//        relationService.list(Wrappers.<Relation>lambdaQuery().in())
        List<List<StoreProduct>> partition = ListUtils.partition(productList, 1000);

        List<Integer> needDelList = new ArrayList<>();
        for (List<StoreProduct> storeProducts : partition) {
            List<Integer> productIds = storeProducts.stream().map(k -> k.getId()).collect(Collectors.toList());
            // 查询出sku
            List<StoreProductAttrValue> skuList = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().in(StoreProductAttrValue::getProductId, productIds));
            if (CollectionUtils.isEmpty(skuList)){
                log.error("未查询到sku数据");
                continue;
            }
            List<String> skuIds = skuList.stream().map(k -> String.valueOf(k.getId())).collect(Collectors.toList());
            List<Relation> relationList = relationService.list(Wrappers.<Relation>lambdaQuery().eq(Relation::getBusinessType, BusinessTypeEnums.PUSH_SKU_PLAT_OF_BY.getCode())
                    .in(Relation::getBusinessCode,skuIds));
            Map<String, Relation> relationMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(relationMap)){
                relationMap = relationList.stream().collect(Collectors.toMap(Relation::getBusinessCode, v->v));
            }
            for (StoreProductAttrValue storeProductAttrValue : skuList) {
                String sourceSkuId = storeProductAttrValue.getSourceSkuId();
                if (sourceSkuId.startsWith("23-23-")){
                    if (relationMap.containsKey(String.valueOf(storeProductAttrValue.getId()))){
                        log.error("重点排查：{}",storeProductAttrValue.getId());
                        continue;
                    }
                    needDelList.add(storeProductAttrValue.getId());
                }
            }
        }
        log.error("需要删除的数据：{}",JSON.toJSONString(needDelList));
        if (CollectionUtils.isNotEmpty(needDelList)){
            // 删除
            List<List<Integer>> partition1 = ListUtils.partition(needDelList, 500);
            for (List<Integer> integers : partition1) {
                storeProductAttrValueService.removeByIds(integers);
            }

        }
        log.error("删除完成：{}",JSON.toJSONString(needDelList));
    }

    private List<Sku> msg = new ArrayList<>();

    public void fix(){
        List<Relation> relationList = relationService.list(Wrappers.<Relation>lambdaQuery().eq(Relation::getBusinessType, BusinessTypeEnums.PUSH_PRODUCT_PLAT_OF_BY.getCode()));
        List<String> needDown = new ArrayList<>();
        boolean flag = false;
        for (Relation relation : relationList) {
            if (flag){
                return;
            }
            String merchantProductId = relation.getFeature("merchantProductId");
            if (StringUtils.isBlank(merchantProductId)){
                log.error("{}商品数据缺失",relation.getBusinessCode());
                continue;
            }
            String reslut = get(platUrl + "/inventory/api/v1/products/"+merchantProductId+"/skus", "");
            if (StringUtils.isBlank(reslut)){
                log.error("{}商品下sku查询失败,merchantProductId: {} ",relation.getBusinessCode(),merchantProductId);
                continue;
            }
            List<Sku> platSkus = JSON.parseArray(reslut, Sku.class);

            List<Integer> skuIds = new ArrayList<>();
            for (Sku sku : platSkus) {
                String[] split = sku.getMerchantSkuId().split("SUYUN");
                if (split.length<2){
                    continue;
                }
                skuIds.add(Integer.valueOf(split[1]));
            }
            if (CollectionUtils.isEmpty(skuIds)){
                log.error("{}老商品,merchantProductId: {} ",relation.getBusinessCode(),merchantProductId);
                continue;
            }
            List<StoreProductAttrValue> skuList = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().in(StoreProductAttrValue::getId, skuIds));
            if (CollectionUtils.isEmpty(skuIds)){
                // 下架
                doDownSkusV2(merchantProductId,platSkus);
            }
            Map<String, StoreProductAttrValue> skuMap = skuList.stream().collect(Collectors.toMap(k -> "SUYUN" + k.getId(), v -> v));
            List<Sku> needDownSku = new ArrayList<>();
            for (Sku skus : platSkus) {
                String merchantSkuId = skus.getMerchantSkuId();
                if (!skuMap.containsKey(merchantSkuId)){
                    needDownSku.add(skus);
                    // 匹配新数据

                    continue;
                }

            }
            if (CollectionUtils.isNotEmpty(needDownSku)){
                doDownSkusV2(merchantProductId,needDownSku);
            }


        }
        log.error("统计数据：{}",JSON.toJSONString(msg));

    }


    public void fixV2(){
        List<Relation> relationList = relationService.list(Wrappers.<Relation>lambdaQuery().eq(Relation::getBusinessType, BusinessTypeEnums.PUSH_PRODUCT_PLAT_OF_BY.getCode()));
        List<String> needDown = new ArrayList<>();
        boolean flag = false;
        Map<Integer, Integer> needUpdateIds = new HashMap<>();
        for (Relation relation : relationList) {
            if (flag){
                return;
            }
            String merchantProductId = relation.getFeature("merchantProductId");
            if (StringUtils.isBlank(merchantProductId)){
                log.error("{}商品数据缺失",relation.getBusinessCode());
                continue;
            }
            String reslut = get(platUrl + "/inventory/api/v1/products/"+merchantProductId+"/skus", "");
            if (StringUtils.isBlank(reslut)){
                log.error("{}商品下sku查询失败,merchantProductId: {} ",relation.getBusinessCode(),merchantProductId);
                continue;
            }
            List<Sku> platSkus = JSON.parseArray(reslut, Sku.class);

            List<Integer> skuIds = new ArrayList<>();
            for (Sku sku : platSkus) {
                String[] split = sku.getMerchantSkuId().split("SUYUN");
                if (split.length<2){
                    continue;
                }
                skuIds.add(Integer.valueOf(split[1]));
            }
            if (CollectionUtils.isEmpty(skuIds)){
                log.error("{}老商品,merchantProductId: {} ",relation.getBusinessCode(),merchantProductId);
                continue;
            }
            StoreProduct storeProduct = storeProductService.getById(relation.getBusinessCode());
            if (null == storeProduct){
                continue;
            }
            List<StoreProductAttrValue> srcSkuList = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(StoreProductAttrValue::getProductId, storeProduct.getId()));
            List<StoreProductAttrValue> skuList = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().in(StoreProductAttrValue::getId, skuIds));
            if (CollectionUtils.isEmpty(skuIds)){
                // 下架
//                doDownSkusV2(merchantProductId,platSkus);
                for (Sku skus : platSkus) {
                    List<SaleAttribute> saleAttributes = skus.getSaleAttributes();
                    Map<String, String> attributeMap = saleAttributes.stream().collect(Collectors.toMap(SaleAttribute::getKey, SaleAttribute::getName));
                    String attrValue = attributeMap.get("SIZE");
                    if (StringUtils.isBlank(attrValue)){
                        attrValue = attributeMap.get("COLOR");
                    }
                    String[] split = skus.getMerchantSkuId().split("SUYUN");
                    if (split.length<2){
                        continue;
                    }
                    for (StoreProductAttrValue storeProductAttrValue : srcSkuList) {
                        if (storeProductAttrValue.getSuk().contains(attrValue)){
                            needUpdateIds.put(storeProductAttrValue.getId(),Integer.valueOf(split[1]));
                            break;
                        }
                    }
                }
            }
            Map<String, StoreProductAttrValue> skuMap = skuList.stream().collect(Collectors.toMap(k -> "SUYUN" + k.getId(), v -> v));

            for (Sku skus : platSkus) {
                String merchantSkuId = skus.getMerchantSkuId();
                if (!skuMap.containsKey(merchantSkuId)){
                    List<SaleAttribute> saleAttributes = skus.getSaleAttributes();
                    Map<String, String> attributeMap = saleAttributes.stream().collect(Collectors.toMap(SaleAttribute::getKey, SaleAttribute::getName));
                    String attrValue = attributeMap.get("SIZE");
                    if (StringUtils.isBlank(attrValue)){
                        attrValue = attributeMap.get("COLOR");
                    }
                    String[] split = skus.getMerchantSkuId().split("SUYUN");
                    if (split.length<2){
                        continue;
                    }
                    for (StoreProductAttrValue storeProductAttrValue : srcSkuList) {
                        if (storeProductAttrValue.getSuk().contains(attrValue)){
                            needUpdateIds.put(storeProductAttrValue.getId(),Integer.valueOf(split[1]));
                            break;
                        }
                    }
                }

            }
//            if (CollectionUtils.isNotEmpty(needDownSku)){
//                doDownSkusV2(merchantProductId,needDownSku);
//            }


        }
        System.out.println(JSON.toJSONString(needUpdateIds));
        for (Map.Entry<Integer, Integer> entry : needUpdateIds.entrySet()) {
            Integer key = entry.getKey();

            Integer value = entry.getValue();
            StoreProductAttrValue storeProductAttrValue = storeProductAttrValueService.getById(key);
            if (null == storeProductAttrValue){
                continue;
            }
            boolean update = storeProductAttrValueService.lambdaUpdate().eq(StoreProductAttrValue::getId, key).set(StoreProductAttrValue::getId, value).update();
            System.out.println();

        }

    }

    private void doDownSkusV2(String merchantProductId,List<Sku> downSkus) {
        boolean flag = false;
        for (Sku skus : downSkus) {
            if (flag){
                log.error("商品不匹配：{}，skuId：{}",merchantProductId,skus.getMerchantSkuId());
                msg.add(skus);
                continue;
            }
            Sku sku = new Sku();
            sku.setStatus(ByCommonConstant.PLAT_UNAVAILABLE);
            sku.setStockNum(0);
            String skuId = skus.getMerchantSkuId();
            try {
                Thread.sleep(RandomUtils.nextInt(10,100));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            String post = post(String.format(platUrl + "/inventory/api/v1/products/%s/skus/%s", merchantProductId, skuId), JSON.toJSONString(sku));
            Sku platSku = JSON.parseObject(post, Sku.class);
            String merchantSkuId = platSku.getMerchantSkuId();
            String[] split = merchantSkuId.split("SUYUN");

            if (StringUtils.isNotBlank(platSku.getId())){
                Relation relation = relationService.getOne(Wrappers.<Relation>lambdaQuery().eq(Relation::getBusinessCode, split[1]).eq(Relation::getBusinessType, BusinessTypeEnums.PUSH_SKU_PLAT_OF_BY.getCode()));
                if (relation == null){
                    relation = Relation.buildRelation(split[1], BusinessTypeEnums.PUSH_SKU_PLAT_OF_BY, PlatPushStatusEnums.BY_DOWN.getCode());
                    relation.addFeature(ByCommonConstant.PUSH_PLAT,"N");
                    relation.addFeature(ByCommonConstant.ORIGIN_STOCK,String.valueOf(platSku.getStockNum()));
//                relation.addFeature(ByCommonConstant.PUSH_PRICE,String.valueOf(storeProductAttrValue.getPrice()));
                    relation.addFeature(ByCommonConstant.PLAT_SKU_ID,platSku.getId());
                    relation.addFeature(ByCommonConstant.MERCHANT_SKU_ID,platSku.getMerchantSkuId());
                    if (null != platSku.getSalePrice()){
                        relation.addFeature(ByCommonConstant.PLAT_SALE_PRICE,String.valueOf(platSku.getSalePrice().getValue()));
                    }
                    if (null != platSku.getOriginalPrice()){
                        relation.addFeature(ByCommonConstant.PLAT_ORIGINAL_PRICE,String.valueOf(platSku.getOriginalPrice().getValue()));
                    }
                    relation.addFeature("reason","ID_NOT_MATCH");
                    relationService.save(relation);
                }else {
                    relation.addFeature(ByCommonConstant.ORIGIN_STOCK,"0");
                    relation.addFeature(ByCommonConstant.PUSH_PLAT,"N");
                    relation.setSubCode(PlatPushStatusEnums.BY_DOWN.getCode());
                    relation.addFeature("reason","ID_NOT_MATCH");
                    relationService.updateById(relation);
                }
            }
        }
    }
    private void doDownSkus(String merchantProductId,List<StoreProductAttrValue> downSkus) {
        for (StoreProductAttrValue skus : downSkus) {
            Sku sku = new Sku();
            sku.setStatus(ByCommonConstant.PLAT_UNAVAILABLE);
            sku.setStockNum(0);
            String skuId = skus.getPushRelation().getFeature(ByCommonConstant.MERCHANT_SKU_ID);
            try {
                Thread.sleep(RandomUtils.nextInt(10,100));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            String post = post(String.format(platUrl + "/inventory/api/v1/products/%s/skus/%s", merchantProductId, skuId), JSON.toJSONString(sku));
            Sku platSku = JSON.parseObject(post, Sku.class);
            if (null != platSku && StringUtils.isNotBlank(platSku.getId())){
                skus.getPushRelation().addFeature(ByCommonConstant.ORIGIN_STOCK,"0");
                skus.getPushRelation().addFeature(ByCommonConstant.PUSH_PLAT,"N");
                skus.getPushRelation().setSubCode(PlatPushStatusEnums.BY_DOWN.getCode());
                relationService.updateById(skus.getPushRelation());
            }
            DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT,"别样sku下架返回:"+post);
            logger.error("别样sku下架返回:{}",post);
        }

    }


    public static void main(String[] args) {
//        String post = get(platUrl + "/inventory/api/v1/products/2300AB022027/skus", "");
//        List<Sku> apiProduct = JSON.parseArray(post, Sku.class);
//        System.out.println(post);
//        initCategory();
    }

    public void pushMainImage(){
        ImageUploadResponse imageUploadResponse = FileUploadUtils.uploadImageOfBY("https://italytao.oss-cn-shanghai.aliyuncs.com/suyun/%E5%A2%83%E5%A4%96%E4%BA%A7%E5%93%81%E5%85%AC%E5%91%8A.jpg");
        List<Relation> relationList = relationService.list(Wrappers.<Relation>lambdaQuery().eq(Relation::getBusinessType, BusinessTypeEnums.PUSH_PRODUCT_PLAT_OF_BY.getCode()));
        for (Relation relation : relationList) {
            if (Objects.equals(relation.getFeature("pushNoticeImage"),"Y")){
                System.out.println("已经上传过了");
                continue;
            }
            String merchantProductId = relation.getFeature("merchantProductId");
            String platProductId = relation.getFeature("platProductId");

            try {
                String reslut = get(platUrl + "/inventory/api/v1/products/"+merchantProductId, "");
                ApiProduct apiProduct = JSON.parseObject(reslut, ApiProduct.class);
                ApiProduct newApiProduct = new ApiProduct();
                newApiProduct.setId(apiProduct.getId());
                newApiProduct.setMerchantProductId(apiProduct.getMerchantProductId());
                List<LayerDTO> layers = apiProduct.getDescription().getLayers();
                if (layers.size()>=2){
                    if (layers.get(1)!=null && layers.get(1).getImage()!=null && Objects.equals(layers.get(1).getImage().getUrl(),"https://5thave-img-cdn-g.bybieyang.com/pf/992abf45-34c9-3dda-ba41-08ca23580917.jpg")){
                        relation.addFeature("pushNoticeImage","Y");
                        relationService.updateById(relation);
                        continue;
                    }
                }
                LayerDTO layerDTO = layers.get(0);
                LayerDTO newLayerDTO = new LayerDTO();
                ImageDTO imageDTO = new ImageDTO();
                imageDTO.setUrl(imageUploadResponse.getUrl());
                imageDTO.setFormat(imageUploadResponse.getFormat());
                imageDTO.setWidth(imageUploadResponse.getWidth());
                imageDTO.setHeight(imageUploadResponse.getHeight());
                newLayerDTO.setImage(imageDTO);
                newLayerDTO.setLayerType("IMAGE");
                if (Objects.equals(layerDTO.getLayerType(),"TEXT")){
                    layers.add(1,newLayerDTO);
                }else {
                    layers.add(0,newLayerDTO);
                }
                newApiProduct.setDescription(apiProduct.getDescription());
                String update = post(platUrl + "/inventory/api/v1/products/"+merchantProductId, JSON.toJSONString(newApiProduct));
                if (StringUtils.isNotEmpty(update)&&update.contains(merchantProductId)){
                    relation.addFeature("pushNoticeImage","Y");
                    relationService.updateById(relation);
                }
                System.out.println(update);
            }catch (Exception e){
                log.error("推送店铺公告异常：",e);
            }

        }


    }

    private static void initCategory(){
        try {
            FileInputStream fis = new FileInputStream(new File("D:\\bieyang\\商品导出_20240619164933.xlsx")); //替换为你的Excel文件路径
            //创建一个工作簿
            Workbook workbook = new XSSFWorkbook(fis);
            //获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            int index = 0;
            for (Row cells : sheet) {
                index++;
                if (index == 1){
                    continue;
                }
                if (null==cells.getCell(0)){
                    continue;
                }
                cells.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                String productId = cells.getCell(0).getStringCellValue();
                cells.getCell(8).setCellType(Cell.CELL_TYPE_STRING);
                String price = cells.getCell(8).getStringCellValue();
                cells.getCell(12).setCellType(Cell.CELL_TYPE_STRING);
                String sku = cells.getCell(12).getStringCellValue();
                System.out.println(productId+"----"+price+"-----"+sku);

            }

            workbook.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void initCustoms(){
        try {
            FileInputStream fis = new FileInputStream(new File("D:\\bieyang\\账册1.xlsx")); //替换为你的Excel文件路径
            //创建一个工作簿
            Workbook workbook = new XSSFWorkbook(fis);
            //获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            int index = 0;
            List<CustomsRecord> customsRecords = new ArrayList<>();
            List<String> barCode = new ArrayList<>();
            for (Row cells : sheet) {
                index++;
                if (index == 1){
                    continue;
                }
                if (null==cells.getCell(0)){
                    continue;
                }
                cells.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                String serialId = cells.getCell(0).getStringCellValue();
                cells.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                String barcode = cells.getCell(1).getStringCellValue();
                cells.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                String uniqNo = cells.getCell(2).getStringCellValue();
                cells.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
                String goodsName = cells.getCell(3).getStringCellValue();
                cells.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
                String brandName = cells.getCell(4).getStringCellValue();
                cells.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
                String categoryName = cells.getCell(5).getStringCellValue();
                cells.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
                String special = cells.getCell(6).getStringCellValue();
                cells.getCell(7).setCellType(Cell.CELL_TYPE_STRING);
                String declareUnit = cells.getCell(7).getStringCellValue();
                cells.getCell(8).setCellType(Cell.CELL_TYPE_STRING);
                String declareQty = cells.getCell(8).getStringCellValue();
                cells.getCell(9).setCellType(Cell.CELL_TYPE_STRING);
                String unit1 = cells.getCell(9).getStringCellValue();
                cells.getCell(10).setCellType(Cell.CELL_TYPE_STRING);
                String qty1 = cells.getCell(10).getStringCellValue();
                cells.getCell(11).setCellType(Cell.CELL_TYPE_STRING);
                String unit2 = cells.getCell(11).getStringCellValue();
                cells.getCell(12).setCellType(Cell.CELL_TYPE_STRING);
                String qty2 = cells.getCell(12).getStringCellValue();
                cells.getCell(13).setCellType(Cell.CELL_TYPE_STRING);
                String originCountry = cells.getCell(13).getStringCellValue();
                cells.getCell(14).setCellType(Cell.CELL_TYPE_STRING);
                String customsRate = cells.getCell(14).getStringCellValue();
                cells.getCell(15).setCellType(Cell.CELL_TYPE_STRING);
                String hscode = cells.getCell(15).getStringCellValue();
                cells.getCell(17).setCellType(Cell.CELL_TYPE_STRING);
                String goodsExpire = cells.getCell(17).getStringCellValue();
                cells.getCell(18).setCellType(Cell.CELL_TYPE_STRING);
                String weight = cells.getCell(18).getStringCellValue();
                cells.getCell(19).setCellType(Cell.CELL_TYPE_STRING);
                String grossWeight = cells.getCell(19).getStringCellValue();
                cells.getCell(20).setCellType(Cell.CELL_TYPE_STRING);
                String declareRate = cells.getCell(20).getStringCellValue();
                cells.getCell(21).setCellType(Cell.CELL_TYPE_STRING);
                String consumerRate = cells.getCell(21).getStringCellValue();
                cells.getCell(22).setCellType(Cell.CELL_TYPE_STRING);
                String threshold = cells.getCell(22).getStringCellValue();
                cells.getCell(23).setCellType(Cell.CELL_TYPE_STRING);
                String declareClassify = cells.getCell(23).getStringCellValue();

                CustomsRecord customsRecord = new CustomsRecord();
                customsRecord.setSerialId(Integer.parseInt(serialId));
                customsRecord.setBarcode(barcode);
                customsRecord.setUniqNo(uniqNo);
                customsRecord.setGoodsName(goodsName);
                customsRecord.setBrandName(brandName);
                customsRecord.setCategoryName(categoryName);
                customsRecord.setSpecial(special);
                customsRecord.setDeclareUnit(declareUnit);
                customsRecord.setDeclareQty(Integer.parseInt(declareQty));
                customsRecord.setQty1(Double.parseDouble(qty1));
                customsRecord.setUnit1(unit1);
                customsRecord.setQty2(Double.parseDouble(qty2));
                customsRecord.setUnit2(unit2);
                customsRecord.setOriginCountry(originCountry);
                customsRecord.setCustomsRate(Double.parseDouble(customsRate));
                customsRecord.setHscode(hscode);
                customsRecord.setGoodsExpire(Integer.parseInt(goodsExpire));
                customsRecord.setWeight(Double.parseDouble(weight));
                customsRecord.setGrossWeight(Double.parseDouble(grossWeight));
                customsRecord.setDeclareRate(Double.parseDouble(declareRate));
                customsRecord.setConsumerRate(Double.parseDouble(consumerRate));
                customsRecord.setThreshold(Double.parseDouble(threshold));
                customsRecord.setDeclareClassify(declareClassify);
                System.out.println(JSON.toJSONString(customsRecord));
                barCode.add(customsRecord.getBarcode());
                customsRecords.add(customsRecord);

            }
            List<CustomsRecord> list = customRecordService.list(Wrappers.<CustomsRecord>lambdaQuery().in(CustomsRecord::getBarcode, barCode));
            if (CollectionUtils.isNotEmpty(list)){
                List<String> collect = list.stream().map(CustomsRecord::getBarcode).collect(Collectors.toList());
                customsRecords.removeIf(customsRecord -> collect.contains(customsRecord.getBarcode()));
            }
            if (CollectionUtils.isNotEmpty(customsRecords)){
                for (List<CustomsRecord> records : ListUtils.partition(customsRecords, 400)) {
                    customRecordService.saveBatch(records);
                }
            }

            workbook.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




    public void pushSkuIMage(){
        //        ImageUploadResponse imageUploadResponse = FileUploadUtils.uploadImageOfBY("https://italytao.oss-cn-shanghai.aliyuncs.com/suyun/%E5%A2%83%E5%A4%96%E4%BA%A7%E5%93%81%E5%85%AC%E5%91%8A.jpg");
//        System.out.println(imageUploadResponse.getId());
//        String reslut = get(platUrl + "/inventory/api/v1/products/"+"86008720182482082-16"+"/skus", "");
//        List<Sku> platSkus = JSON.parseArray(reslut, Sku.class);
//        for (Sku skus : platSkus) {
//            Sku sku = new Sku();
//            sku.setId(skus.getId());
//            sku.setMerchantSkuId(skus.getMerchantSkuId());
//            sku.setProductId(skus.getProductId());
//            sku.setMerchantSkuId(skus.getMerchantSkuId());
//            ProductImageDTO skuImage = new ProductImageDTO();
//            skuImage.setId(imageUploadResponse.getId());
//            skuImage.setIndex(0);
//            skus.getImages().add(0,skuImage);
//            sku.setImages(skus.getImages());
//            String post = post(String.format(platUrl + "/inventory/api/v1/products/%s/skus/%s", "86008720182482082-16", skus.getMerchantSkuId()), JSON.toJSONString(sku));
//            System.out.println(post);
//        }
    }


    public static String post(String url, String params) {
        MultiValueMap<String,String> header = new LinkedMultiValueMap<>();
        header.put("Authorization",Collections.singletonList(platKey));
        return request(url, params, header, HttpMethod.POST, MediaType.APPLICATION_JSON);
    }
    public static String post(String url, String params, MultiValueMap<String, String> headers) {
        return request(url, params, headers, HttpMethod.POST, MediaType.APPLICATION_JSON);
    }

    public static String get(String url, String params) {
        MultiValueMap<String,String> header = new LinkedMultiValueMap<>();
        header.put("Authorization",Collections.singletonList(platKey));
        return request(url, params, header, HttpMethod.GET, MediaType.APPLICATION_JSON);
    }
    public static String get(String url, String params, MultiValueMap<String, String> headers) {
        return request(url, params, headers, HttpMethod.GET, MediaType.APPLICATION_JSON);
    }

    /**
     * http请求
     *
     * @param url
     * @param params    请求参数
     * @param headers   请求头
     * @param method    请求方式
     * @param mediaType 参数类型
     * @return
     */
    public static String request(String url, Object params, MultiValueMap<String, String> headers, HttpMethod method, MediaType mediaType) {
        if (url == null || url.trim().isEmpty()) {
            return null;
        }
        RestTemplate client = new RestTemplate();
        // header
        HttpHeaders httpHeaders = new HttpHeaders();
        if (headers != null) {
            httpHeaders.addAll(headers);
        }
        // 提交方式：表单、json
        httpHeaders.setContentType(mediaType);
        HttpEntity<Object> httpEntity = new HttpEntity(params, httpHeaders);
        ResponseEntity<String> response = client.exchange(url, method, httpEntity, String.class);
        return response.getBody();
    }

}
